package netWork;

import jdk.internal.util.xml.impl.Input;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 接受图片服务端
 */
public class TcpFileUploadServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务器启动端口号9999");
        //获取socket对象
        Socket socket = serverSocket.accept();
        //将socket对象的内容读取出来
        String destFilePath ="src/tupian.png";
        File file = new File(destFilePath);
        try(BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            ByteArrayOutputStream baos =new ByteArrayOutputStream();
            PrintWriter writer = new PrintWriter(socket.getOutputStream());
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
            int n = 0;
            byte[]b = new byte[4096];
            while ((n = bis.read(b)) != -1){
                baos.write(b,0,n);
            }
            byte[] array = baos.toByteArray();
            //将得到的byte数组写入文件,写入指定文件路径,得到一个文件
            bos.write(array);
            writer.println("收到图片");
            writer.flush();
        }finally {
            serverSocket.close();
            socket.close();
        }
    }
}
